import {Checkbox, Form, Input, message, Modal, Tooltip} from "antd";
import {inject, observer} from "mobx-react";
import React, {Component} from "react";
import {
    LOGIN_BY_ILAB,
    REGIST_USER_MESSAGE,
    RETRIVE_EMAIL,
    USER_LOGIN,
    USER_RETRIVE,
    VERIFICATION_EMAIL
} from "../../api/APIURLDefine";
import {InfoCircleOutlined} from '@ant-design/icons';
import {AxioInstance} from "../../api/AxiosHelper";
import "./index.less"
import {FormInstance} from "antd/es/form";
import $ from "jquery";
import Axios from "axios";
import {LoginType} from "../../stores/GlobalStore";
import Captcha from "../Captcha";

@inject("globalStore", "userStore", "commentStore")
@observer
class LoginModal extends Component<any, any> {
    constructor(props) {
        super(props);
        this.state = {
            isLogin: true,
            isReset: false,
            disable: false,
            isFirst: true,
            loginType: 0, //0 think账号登录 1 ilab账号登录
            time: 60
        }
    }

    Captcha: Captcha;//验证码
    onRef = (ref: any) => {
        this.Captcha = ref;
    };

    registerUser() {
        this.form.resetFields();
        this.setState({isLogin: false, isFirst: true, disable: false});
    }

    LoginUser() {
        this.form.resetFields();
        this.setState({isLogin: true, isReset: false, isFirst: true, disable: false});
    }

    reDrawPic = () => {
        this.Captcha?.reloadPic();
    }

    form: FormInstance = null;

    //获取邮箱验证码
    getEmailCode() {
        let email = this.form?.getFieldValue("email");
        let patt = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
        const isEmail = patt.test(email);
        if (!email || !isEmail) {
            message.error("请输入正确的邮箱")
        } else {
            this.setState({disable: true, isFirst: false});
            this.countDown(60);
            let formData = new FormData();
            formData.append("email", email);
            let path = this.state.isReset ? RETRIVE_EMAIL : VERIFICATION_EMAIL;
            AxioInstance.post(path, formData).then((data: any) => {
                message.success("邮件发送成功，请注意查收")
            }).catch((e) => {
                console.error(e);
                message.error("邮箱验证失败");
            });
        }
    }

    //切换登录方式
    changeLoginType() {
        this.props.globalStore.SetLoginType(LoginType.ILAB);
        // this.setState({loginType: 1});
    }

    countDown = (time: number) => {
        --time;
        // console.log(time);
        if (time !== 0) {
            setTimeout(() => {
                this.setState({time});
                this.countDown(time);
            }, 1000)
        } else {
            this.setState({disable: false, time: ""});
        }
    }

    cancel = () => {
        this.setState({isLogin: true, disable: false, isFirst: true, isReset: false});
        // this.props.globalStore.SetLoginType(LoginType.THINK);
        this.props.globalStore.updateShowLoginModalVisiable(false)
    }

    returnLogin() {
        this.props.globalStore.SetLoginType(LoginType.THINK);
    }

    LoginInIlab(username: string, password: string) {
        const datas = {
            course: this.props.commentStore.courseId,
            username: username,
            password: password
        }
        AxioInstance.post(LOGIN_BY_ILAB, JSON.stringify(datas)).then((resp: any) => {
            //console.log(resp);
            // this.setState({loginType: 0});
            this.props.globalStore.SetLoginType(LoginType.THINK);
            this.props.userStore.setAccessToken(resp.access_token);
            this.props.globalStore.updateShowLoginModalVisiable(false);
            message.success("登录成功");
        }).catch((e) => {
            this.form.setFieldsValue({"password": ""});
            message.error("用户名或密码错误");
        })
    }

    onFinishFailed = (form) => {
        message.error("注册失败")
    }
    //登录页面
    Login = () => {
        setTimeout(() => {
            const rem = $("#basic>div.ant-form-item:last");
            const height = rem.height();
            const top = rem.outerHeight(true);
            $(".forget-btn>a").css({"height": height, "top": -top, "display": "flex", "align-items": "center"})
        }, 200)
        return <Form
            name="basic"
            className="modalForm"
            initialValues={{remember: true}}
            ref={(ref) => this.form = ref}
            onFinish={(form) => {
                const datas = {
                    username: form.username,
                    password: form.password
                }
                AxioInstance.post(USER_LOGIN, JSON.stringify(datas)).then((data: any) => {
                    this.props.userStore.setAccessToken(data.access_token);
                    this.props.globalStore.updateShowLoginModalVisiable(false);
                    message.success("登录成功");
                }).catch((e) => {
                    console.error(e);
                    message.error("登录失败，请重新登录");
                });
            }}
            onFinishFailed={this.onFinishFailed.bind(this)}
        >

            <Form.Item
                name="username"
                rules={[{required: true, message: " "},
                    {pattern: /^[a-z0-9A-Z]{4,16}$/, message: " "}
                ]}
            >
                <Input
                    placeholder={"请输入用户名"}
                    suffix={<Tooltip title="4-16位字母或数字">
                        <InfoCircleOutlined style={{color: "#3e84fd"}}/>
                    </Tooltip>}
                    prefix={<img style={{width: "0.35rem", height: "0.23rem"}}
                                 src={"ui/icon_username.png"}/>}
                    className="modalInput"/>
            </Form.Item>

            <Form.Item
                name="password"
                rules={[{required: true, message: " "}]}
            >
                <Input.Password iconRender={(e) => e ?
                    <img style={{width: "0.23rem", height: "0.18rem"}} src={"ui/icon_open.png"}/> :
                    <img style={{width: "0.23rem", height: "0.18rem"}} src={"ui/icon_hide.png"}/>}
                                placeholder={"请输入密码"}
                                prefix={<img style={{width: "0.35rem", height: "0.23rem"}}
                                             src={"ui/icon_password.png"}/>} className="modalInput"/>
            </Form.Item>

            <Form.Item name="remember" valuePropName="checked">
                <Checkbox style={{marginLeft: "0.45rem", color: "#3e84ff"}}>记住密码</Checkbox>
            </Form.Item>
            <div className="forget-btn">
                <a style={{color: "#3e84ff"}} onClick={() => {
                    this.setState({isReset: true, isFirst: true, disable: false});
                }}>忘记密码?</a>
            </div>
            <div className="buttons"
                 style={{
                     display: "flex",
                     width: "100%",
                     justifyContent: "space-around",
                     position: "relative",
                     top: "-0.3rem"
                 }}>
                <button className="modalButton" type="submit">
                    登录
                </button>
                <button className="modalButton" onClick={this.registerUser.bind(this)}>
                    注册
                </button>
            </div>
            {/* <div className="login-footer">
                <span style={{color: "#3e84ff", marginRight: "0.2rem"}}>其他登录方式</span>
                <img onClick={this.changeLoginType.bind(this)}
                     style={{width: "auto", height: "auto", cursor: "pointer"}}
                     alt={"ilab登录logo"}
                     src={"ui/icon_ilab_logo.png"}/>
            </div>*/}
        </Form>
    }
    //ilab账号登录
    LoginByIlab = () => {
        return <Form
            name="basic"
            className="modalForm"
            style={{paddingTop: "0.5rem", marginRight: "0.67rem"}}
            initialValues={{remember: true}}
            ref={(ref) => this.form = ref}
            onFinish={(form) => {
                this.LoginInIlab(form.userName, form.password);
            }}
            onFinishFailed={this.onFinishFailed.bind(this)}
        >
            <Form.Item
                name="userName"
                rules={[{required: true, message: " "},
                    {pattern: /^[a-z0-9A-Z]{4,16}$/, message: " "}
                ]}
            >
                <Input
                    placeholder={"请输入用户名"}
                    suffix={<Tooltip title="4-16位字母或数字">
                        <InfoCircleOutlined style={{color: "#3e84fd"}}/>
                    </Tooltip>}
                    prefix={<img style={{width: "0.35rem", height: "0.23rem"}}
                                 src={"ui/icon_username.png"}/>}
                    className="modalInput"/>
            </Form.Item>

            <Form.Item
                name="password"
                rules={[{required: true, message: " "}]}
            >
                <Input.Password iconRender={(e) => e ?
                    <img style={{width: "0.23rem", height: "0.18rem"}} src={"ui/icon_open.png"}/> :
                    <img style={{width: "0.23rem", height: "0.18rem"}} src={"ui/icon_hide.png"}/>}
                                placeholder={"请输入密码"}
                                prefix={<img style={{width: "0.35rem", height: "0.23rem"}}
                                             src={"ui/icon_password.png"}/>} className="modalInput"/>
            </Form.Item>
            <Form.Item name="remember" valuePropName="checked">
                <Checkbox style={{marginLeft: "0.45rem", color: "#3e84ff"}}>记住密码</Checkbox>
            </Form.Item>
            <Form.Item>
                <div className="buttons" style={{display: "flex", marginTop: "0.2rem", justifyContent: "space-around"}}>
                    <button className="modalButton" type="submit">
                        登录
                    </button>
                    <button className="modalButton" type="button" onClick={() => {
                        const user = this.props.userStore;
                        if (user.testAccount)
                            this.LoginInIlab(user.testAccount, user.user.testPwd)
                        else
                            this.LoginInIlab("15691837355", "Zeg391239")
                    }}>
                        专家入口
                    </button>
                </div>
                {/*<div className="login-footer">
                    <span style={{color: "#3e84ff", marginRight: "0.2rem"}}>默认登录方式</span>
                    <img onClick={() => {
                        this.props.globalStore.SetLoginType(LoginType.THINK);
                    }}
                         style={{width: "2.1rem", height: "0.5rem", cursor: "pointer"}}
                         alt={"think登录logo"}
                         src={"ui/icon_think_logo.png"}/>
                </div>*/}
            </Form.Item>
        </Form>
    }
    //注册
    Register = () => {
        const REGISTER_BY_EMAIL = this.props.globalStore.RegisterByEmail;
        setTimeout(() => {
            let btn = $(".login-code-btn");
            if (btn) {
                const bro = btn.prev();
                btn.css("height", bro.height())
            }
        }, 200)
        return <Form
            name="basic"
            className="modalForm modalForm-Register"
            initialValues={{remember: true}}
            ref={(ref) => this.form = ref}
            onFinish={(form) => {
                // console.log(form.password);
                if (!REGISTER_BY_EMAIL && !this.Captcha.CheckCode(form.captcha)) {
                    message.error("验证码错误");
                    this.form?.resetFields(["captcha"]);
                    return;
                }
                if (form.password === form.confirmPassword) {
                    let formData = new FormData();
                    for (let key in form) {
                        formData.append(key, form[key]);
                    }
                    if (REGISTER_BY_EMAIL) {
                        formData.append("emailCode", "code");
                        formData.append("email", "default");
                    }

                    Axios({
                        method: 'post',
                        url: REGIST_USER_MESSAGE,
                        //    必不可少，修改数据的提交方式
                        headers: {
                            "Content-Type": 'application/x-www-form-urlencoded; charset=UTF-8'
                        },
                        data: formData
                    }).then((resp: any) => {
                        //(resp)
                        if (resp.data.code === 10000) {
                            message.success("注册成功");
                            this.setState({isLogin: true});
                        } else {
                            message.error(resp.data.msg);
                            this.form.setFieldsValue({"password": "", "confirmPassword": ""})
                        }
                    }).catch((e) => {
                        message.error("注册失败")
                        console.error(e);
                    });

                } else {
                    message.error("两次输入的密码不一致");
                    this.form.setFieldsValue({"password": "", "confirmPassword": ""})
                }
            }}
            onFinishFailed={this.onFinishFailed.bind(this)}
        >
            <Form.Item
                name="username"
                rules={[{required: true, message: " "},
                    {pattern: /^[a-z0-9A-Z]{6,16}$/, message: " "}
                ]}
            >
                <Input
                    placeholder={"请输入用户名"}
                    suffix={<Tooltip title="6-16位字母或数字">
                        <InfoCircleOutlined style={{color: "#3e84fd"}}/>
                    </Tooltip>}
                    prefix={<img style={{width: "0.35rem", height: "0.23rem"}}
                                 src={"ui/icon_username.png"}/>}
                    className="modalInput"/>
            </Form.Item>

            <Form.Item
                name="password"
                rules={[{required: true, message: " "}]}
            >
                <Input.Password iconRender={(e) => e ?
                    <img style={{width: "0.23rem", height: "0.18rem"}} src={"ui/icon_open.png"}/> :
                    <img style={{width: "0.23rem", height: "0.18rem"}} src={"ui/icon_hide.png"}/>}
                                placeholder={"请输入密码"}
                                prefix={<img style={{width: "0.35rem", height: "0.23rem"}}
                                             src={"ui/icon_password.png"}/>} className="modalInput"/>
            </Form.Item>
            <Form.Item
                name="confirmPassword"
                rules={[{required: true, message: " "}]}
            >
                <Input.Password iconRender={(e) => e ?
                    <img style={{width: "0.23rem", height: "0.18rem"}} src={"ui/icon_open.png"}/> :
                    <img style={{width: "0.23rem", height: "0.18rem"}} src={"ui/icon_hide.png"}/>}
                                placeholder={"请输入确认密码"}
                                prefix={<img style={{width: "0.35rem", height: "0.23rem"}}
                                             src={"ui/icon_password.png"}/>} className="modalInput"/>
            </Form.Item>
            {
                REGISTER_BY_EMAIL ?
                    <div>
                        <Form.Item
                            name="email"
                            rules={[{required: true, message: " "},
                                {pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: " "}
                            ]}
                        >
                            <Input
                                style={{width: "3rem"}}
                                placeholder={"请输入邮箱"}
                                className="modalInput"/>
                        </Form.Item>
                        <button
                            id="code"
                            type={"button"}
                            className="login-code-btn"
                            disabled={this.state.disable}
                            onClick={this.getEmailCode.bind(this)}
                            style={{}}>
                            {
                                this.state.isFirst ? "获取验证码" : `重新发送${this.state.time}`
                            }
                        </button>
                        <Form.Item
                            name="emailCode"
                            style={{marginTop: "-0.42rem"}}
                            rules={[{required: true, message: " "}
                            ]}
                        >
                            <Input
                                placeholder={"请输入邮箱验证码"}
                                className="modalInput"/>
                        </Form.Item>
                    </div> : <div>

                        <Form.Item>
                            <div style={{width: "100%", height: "100%", paddingLeft: "0.3rem"}}>
                                <Captcha onRef={this.onRef}/>
                            </div>
                            <div id="captcha-btn" style={{display: "grid", placeItems: "center"}}>
                                <button
                                    id="code"
                                    type={"button"}
                                    className="login-captcha-btn"
                                    disabled={this.state.disable}
                                    onClick={this.reDrawPic}>
                                    看不清，点击刷新
                                </button>
                            </div>
                        </Form.Item>

                        <Form.Item
                            name="captcha"
                            rules={[{required: true, message: " "}
                            ]}
                        >
                            <Input
                                placeholder={"请输入验证码"}
                                className="modalInput"/>
                        </Form.Item>
                    </div>
            }

            <Form.Item>
                <div className="buttons"
                     style={{display: "flex", justifyContent: "space-around"}}>
                    <button className="modalButton" type="submit">
                        注册
                    </button>
                    <button className="modalButton" onClick={() => {
                        this.form.resetFields();
                        this.setState({isLogin: true});
                    }}>
                        返回登录
                    </button>
                </div>
            </Form.Item>
        </Form>
    }
    //找回密码
    ResetPassword = () => {
        setTimeout(() => {
            let btn = $(".login-code-btn");
            if (btn) {
                const bro = btn.prev();
                btn.css("height", bro.height())
            }
        }, 200)
        return <Form
            name="basic"
            className="modalForm"
            initialValues={{remember: true}}
            ref={(ref) => this.form = ref}
            onFinish={(form) => {
                if (form.password === form.confirmPassword) {
                    let formData = new FormData();
                    for (let key in form) {
                        formData.append(key, form[key]);
                    }
                    Axios({
                        method: 'post',
                        url: USER_RETRIVE,
                        //    必不可少，修改数据的提交方式
                        headers: {
                            "Content-Type": 'application/x-www-form-urlencoded; charset=UTF-8'
                        },
                        data: formData
                    }).then((resp: any) => {
                        //(resp)
                        if (resp.data.code === 10000) {
                            message.success("重置密码成功");
                            this.setState({isLogin: true, isReset: false});
                        } else {
                            message.error(resp.data.msg);
                            this.form.setFieldsValue({"password": "", "confirmPassword": ""})
                        }
                    }).catch((e) => console.error(e));

                } else {
                    message.error("两次输入的密码不一致");
                    this.form.setFieldsValue({"password": "", "confirmPassword": ""})
                }
            }}
            onFinishFailed={this.onFinishFailed.bind(this)}
        >
            <Form.Item
                name="username"
                rules={[{required: true, message: " "},
                    {pattern: /^[a-z0-9A-Z]{6,16}$/, message: " "}
                ]}
            >
                <Input
                    placeholder={"请输入用户名"}
                    suffix={<Tooltip title="6-16位字母或数字">
                        <InfoCircleOutlined style={{color: "#3e84fd"}}/>
                    </Tooltip>}
                    prefix={<img style={{width: "0.35rem", height: "0.23rem"}}
                                 src={"ui/icon_username.png"}/>}
                    className="modalInput"/>
            </Form.Item>


            <Form.Item
                name="email"
                rules={[{required: true, message: " "},
                    {pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: " "}
                ]}
            >
                <Input
                    style={{width: "3rem"}}
                    placeholder={"请输入邮箱"}
                    className="modalInput"/>
            </Form.Item>
            <button
                id="code"
                type={"button"}
                className="login-code-btn"
                disabled={this.state.disable}
                onClick={this.getEmailCode.bind(this)}
                style={{top: "-0.7rem"}}>
                {
                    this.state.isFirst ? "获取验证码" : `重新发送${this.state.time}`
                }
            </button>
            <Form.Item
                name="emailCode"
                style={{marginTop: "-0.42rem"}}
                rules={[{required: true, message: " "}
                ]}
            >
                <Input

                    placeholder={"请输入邮箱验证码"}
                    className="modalInput"/>
            </Form.Item>
            <Form.Item
                name="password"
                rules={[{required: true, message: " "}]}
            >
                <Input.Password iconRender={(e) => e ?
                    <img style={{width: "0.23rem", height: "0.18rem"}} src={"ui/icon_open.png"}/> :
                    <img style={{width: "0.23rem", height: "0.18rem"}} src={"ui/icon_hide.png"}/>}
                                placeholder={"请输入密码"}
                                prefix={<img style={{width: "0.35rem", height: "0.23rem"}}
                                             src={"ui/icon_password.png"}/>} className="modalInput"/>
            </Form.Item>
            <Form.Item
                name="confirmPassword"
                rules={[{required: true, message: " "}]}
            >
                <Input.Password iconRender={(e) => e ?
                    <img style={{width: "0.23rem", height: "0.18rem"}} src={"ui/icon_open.png"}/> :
                    <img style={{width: "0.23rem", height: "0.18rem"}} src={"ui/icon_hide.png"}/>}
                                placeholder={"请输入确认密码"}
                                prefix={<img style={{width: "0.35rem", height: "0.23rem"}}
                                             src={"ui/icon_password.png"}/>} className="modalInput"/>
            </Form.Item>
            <Form.Item>
                <div className="buttons"
                     style={{display: "flex", justifyContent: "space-around"}}>
                    <button className="modalButton" type="submit">
                        重置密码
                    </button>
                    <button className="modalButton" onClick={() => {
                        this.LoginUser();
                    }}>
                        返回登录
                    </button>
                </div>
            </Form.Item>
        </Form>
    }

    render() {
        const Login = this.Login;
        const LoginByIlab = this.LoginByIlab;
        const Register = this.Register;
        const ResetPassword = this.ResetPassword;
        const {isLogin, isReset} = this.state;
        return (
            <Modal onCancel={this.cancel.bind(this)}
                   footer={null}
                   visible={this.props.globalStore.showLoginModal}
                   className={this.props.globalStore.loginType === LoginType.THINK ? "modal" : "modal-ilab"}
                   width="13.76rem"
                   closable={false}
                   maskClosable={false}
                   keyboard={false}
                   destroyOnClose={true}
                   bodyStyle={{
                       backgroundSize: "100% 100%",
                       height: "7.28rem"
                   }}>
                <div id="loginModal">
                    <img src={"./ui/icon_close.png"}
                         onClick={this.cancel.bind(this)}
                         className="modalCloseButton"/>
                    {
                        isLogin ? isReset ? <ResetPassword/> : this.props.globalStore.loginType === LoginType.THINK ?
                            <Login/> : <LoginByIlab/> : <Register/>
                    }

                </div>
            </Modal>
        );
    }
}

export default LoginModal;
